package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bf.electroplating.login.UserContext;
import com.bf.electroplating.mapper.*;
import com.bf.electroplating.pojo.dto.company.ComCompanyDTO;
import com.bf.electroplating.pojo.entity.*;
import com.bf.electroplating.pojo.enums.AttModuleEnums;
import com.bf.electroplating.pojo.enums.DicTypeEnums;
import com.bf.electroplating.pojo.enums.IndustryTypeEnum;
import com.bf.electroplating.pojo.vo.SelectVo;
import com.bf.electroplating.pojo.vo.company.ComCompanyVO;
import com.bf.electroplating.service.*;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import jakarta.annotation.Resource;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 15451
 * @description 针对表【com_company(表注释信息可根据实际情况补充)】的数据库操作Service实现
 * @createDate 2025-05-09 11:11:32
 */
@Service
public class ComCompanyServiceImpl extends ServiceImpl<ComCompanyMapper, ComCompany>
        implements ComCompanyService {

    @Resource
    private PubAttachmentService attachmentService;
    @Resource
    private PubAttachmentRelService attachmentRelService;

    // 注入所有包含companyId的实体对应的Service
    @Resource
    private ParkContingencyTeamMapper parkContingencyTeamService;
    @Resource
    private InspectionTaskMapper inspectionTaskService;
    @Resource
    private InspectionTaskCompanyMapper inspectionTaskCompanyMapper;
    @Resource
    private InspectionFeedbackMapper inspectionFeedbackService;
    @Resource
    private ControlProblemFindingMapper controlProblemFindingService;
    @Resource
    private ComWorkshopMapper comWorkshopService;
    @Resource
    private ComProductionMapper comProductionService;
    @Resource
    private ComExaminingReportMapper comExaminingReportService;
    @Resource
    private ComEnvironmentallyFacilityMapper comEnvironmentallyFacilityService;
    @Resource
    private ComEnvironmentallyExamineMapper comEnvironmentallyExamineService;
    @Resource
    private ComDischargePermitMapper comDischargePermitService;
    @Resource
    private ComContingencyPlanMapper comContingencyPlanService;
    @Resource
    private ComContingencySpaceFacilityMapper comContingencySpaceFacilityService;
    @Resource
    private PubParamDictionaryService pubParamDictionaryService;

    @Override
    public Page<ComCompanyVO> getCompanyList(ComCompanyDTO dto) {
        Page<ComCompany> page = new Page<>(dto.getPageNum(), dto.getPageSize());
        LambdaQueryWrapper<ComCompany> wrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(dto.getCompanyName())) {
            wrapper.like(ComCompany::getCompanyName, dto.getCompanyName());
        }
        if (StringUtils.hasText(dto.getOrganizationCode())) {
            wrapper.eq(ComCompany::getOrganizationCode, dto.getOrganizationCode());
        }
        if (StringUtils.hasText(dto.getIndustryType())) {
            wrapper.eq(ComCompany::getIndustryType, dto.getIndustryType());
        }
        Page<ComCompany> companyPage = this.page(page, wrapper);
        Page<ComCompanyVO> voPage = new Page<>();
        BeanUtils.copyProperties(companyPage, voPage, "records");
        List<ComCompanyVO> voList = companyPage.getRecords().stream().map(company -> {
            ComCompanyVO vo = new ComCompanyVO();
            BeanUtils.copyProperties(company, vo);
            vo.setIndustryType(IndustryTypeEnum.getDesc(company.getIndustryType()));
            vo.setPollutionDischargeInfo(getPollutionTypeByCode(company.getPollutionDischargeInfo()));
            vo.setAttachmentIds(attachmentService.getWholeFile(company.getId(), AttModuleEnums.COMPANY.getCode()));
            return vo;
        }).collect(Collectors.toList());
        voPage.setRecords(voList);
        return voPage;
    }

    private List<String> getPollutionTypeByCode(String pollutionDischargeInfo) {
        String[] split = pollutionDischargeInfo.split(",");
        List<String> pollutionTypeList = new ArrayList<>();
        if (split!=null && split.length>0) {
            for (int i = 0; i < split.length; i++) {
                String temp=split[i].trim();
                temp=pubParamDictionaryService.getNameByModuleAndCode(DicTypeEnums.PWLX.getCode(),temp);
                pollutionTypeList.add(temp);
            }
        }
        return pollutionTypeList;
    }

    @Override
    public ComCompanyVO getCompanyById(String id) {
        ComCompany company = this.getById(id);
        if (company == null) {
            return null;
        }
        ComCompanyVO vo = new ComCompanyVO();
        BeanUtils.copyProperties(company, vo);
        vo.setPollutionDischargeInfo(getPollutionTypeByCode(company.getPollutionDischargeInfo()));
        vo.setAttachmentIds(attachmentService.getWholeFile(company.getId(), AttModuleEnums.COMPANY.getCode()));
        return vo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveCompany(ComCompanyVO vo) {
        ComCompany company = new ComCompany();
        BeanUtils.copyProperties(vo, company);
        String pollutionType=getPollutionType(vo.getPollutionDischargeInfo());
        company.setPollutionDischargeInfo(pollutionType);
        boolean save = save(company);
        attachmentService.saveWholeAttachmentRel(vo.getAttachmentIds(), company.getId(), AttModuleEnums.COMPANY.getCode());
        return save;
    }

    private String getPollutionType(List<String> pollutionDischargeInfo) {
        String pollutionType="";
        if (!CollectionUtils.isEmpty(pollutionDischargeInfo)) {
            for (String item : pollutionDischargeInfo) {
                pollutionType+=item+",";
            }
            pollutionType=pollutionType.substring(0, pollutionType.length()-1);
        }
        return pollutionType;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateCompany(ComCompanyVO vo) {
        ComCompany company = new ComCompany();
        BeanUtils.copyProperties(vo, company);
        String pollutionType=getPollutionType(vo.getPollutionDischargeInfo());
        company.setPollutionDischargeInfo(pollutionType);
        if (vo.getAttachmentIds() != null) {
//            attachmentService.deleteByModuleId(company.getId(), AttModuleEnums.COMPANY.getCode());
            attachmentRelService.remove(new LambdaQueryWrapper<PubAttachmentRel>()
                    .eq(PubAttachmentRel::getStorePath, AttModuleEnums.COMPANY.getCode())
                    .eq(PubAttachmentRel::getRelationId, company.getId()));
            attachmentService.saveWholeAttachmentRel(vo.getAttachmentIds(), company.getId(), AttModuleEnums.COMPANY.getCode());
        }
        return this.updateById(company);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCompany(String id) {
        // 删除公司前，先删除所有相关的数据
        deleteRelatedDataByCompanyId(id);

        // 删除附件关联
        attachmentRelService.remove(new LambdaQueryWrapper<PubAttachmentRel>()
                .eq(PubAttachmentRel::getStorePath, AttModuleEnums.COMPANY.getCode())
                .eq(PubAttachmentRel::getRelationId, id));

        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchDeleteCompany(List<String> ids) {
        // 批量删除公司前，先删除所有相关的数据
        for (String id : ids) {
            deleteRelatedDataByCompanyId(id);

            // 删除附件关联
            attachmentRelService.remove(new LambdaQueryWrapper<PubAttachmentRel>()
                    .eq(PubAttachmentRel::getStorePath, AttModuleEnums.COMPANY.getCode())
                    .eq(PubAttachmentRel::getRelationId, id));
        }

        return this.removeByIds(ids);
    }

    /**
     * 根据公司ID删除所有相关的数据
     *
     * @param companyId 公司ID
     */
    private void deleteRelatedDataByCompanyId(String companyId) {
        // 删除应急队伍数据
        parkContingencyTeamService.delete(new LambdaQueryWrapper<ParkContingencyTeam>()
                .eq(ParkContingencyTeam::getCompanyId, companyId));
        // 删除巡检任务数据
        inspectionTaskService.delete(new LambdaQueryWrapper<InspectionTask>()
                .eq(InspectionTask::getCompanyId, companyId));
        List<InspectionTaskCompany> inspectionTaskCompanies = inspectionTaskCompanyMapper.selectList(new LambdaQueryWrapper<InspectionTaskCompany>()
                .eq(InspectionTaskCompany::getCompanyId, companyId));
        if (inspectionTaskCompanies != null && !inspectionTaskCompanies.isEmpty()){
            inspectionTaskService.deleteById(inspectionTaskCompanies.stream().map(InspectionTaskCompany::getTaskId).toArray());
            inspectionTaskCompanyMapper.delete(new LambdaQueryWrapper<InspectionTaskCompany>()
                    .eq(InspectionTaskCompany::getCompanyId, companyId));
        }

        // 删除巡检反馈数据
        inspectionFeedbackService.delete(new LambdaQueryWrapper<InspectionFeedback>()
                .eq(InspectionFeedback::getCompanyId, companyId));
        inspectionFeedbackService.delete(new LambdaQueryWrapper<InspectionFeedback>()
                .eq(InspectionFeedback::getInspectionPoint, companyId));
        // 删除问题发现数据
        controlProblemFindingService.delete(new LambdaQueryWrapper<ControlProblemFinding>()
                .eq(ControlProblemFinding::getCompanyId, companyId));
        // 删除车间数据
        comWorkshopService.delete(new LambdaQueryWrapper<ComWorkshop>()
                .eq(ComWorkshop::getCompanyId, companyId));
        // 删除生产数据
        comProductionService.delete(new LambdaQueryWrapper<ComProduction>()
                .eq(ComProduction::getCompanyId, companyId));
        // 删除检查报告数据
        comExaminingReportService.delete(new LambdaQueryWrapper<ComExaminingReport>()
                .eq(ComExaminingReport::getCompanyId, companyId));
        // 删除环保设施数据
        comEnvironmentallyFacilityService.delete(new LambdaQueryWrapper<ComEnvironmentallyFacility>()
                .eq(ComEnvironmentallyFacility::getCompanyId, companyId));
        // 删除环境审查数据
        comEnvironmentallyExamineService.delete(new LambdaQueryWrapper<ComEnvironmentallyExamine>()
                .eq(ComEnvironmentallyExamine::getCompanyId, companyId));
        // 删除排污许可证数据
        comDischargePermitService.delete(new LambdaQueryWrapper<ComDischargePermit>()
                .eq(ComDischargePermit::getCompanyId, companyId));
        // 删除应急预案数据
        comContingencyPlanService.delete(new LambdaQueryWrapper<ComContingencyPlan>()
                .eq(ComContingencyPlan::getCompanyId, companyId));
        // 删除应急空间设施数据
        comContingencySpaceFacilityService.delete(new LambdaQueryWrapper<ComContingencySpaceFacility>()
                .eq(ComContingencySpaceFacility::getCompanyId, companyId));
    }

    @Override
    public List<SelectVo> getCompanySelect() {
        LambdaQueryWrapper<ComCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ComCompany::getId, ComCompany::getCompanyName);
        wrapper.eq(ComCompany::getDelFlag, "0");
        List<ComCompany> companies = this.list(wrapper);
        return companies.stream().map(company -> {
            SelectVo selectVo = new SelectVo();
            selectVo.setId(company.getId());
            selectVo.setName(company.getCompanyName());
            selectVo.setAbbr(company.getCompanyAbbreviation());
            return selectVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<SelectVo> selectWaterPlantInfo() {
        LambdaQueryWrapper<ComCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ComCompany::getId, ComCompany::getCompanyName, ComCompany::getOrganizationCode);
        wrapper.eq(ComCompany::getIsSewagePlant, "1");
        wrapper.eq(ComCompany::getDelFlag, "0");
        if (CollectionUtils.isEmpty(UserContext.getUser().getParkFunctionIds())){
            wrapper.eq(ComCompany::getId, UserContext.getUser().getCompanyId());
        }
        List<ComCompany> companies = this.list(wrapper);
        return companies.stream().map(company -> {
            SelectVo selectVo = new SelectVo();
            selectVo.setId(company.getId());
            selectVo.setName(company.getCompanyName());
            selectVo.setCode(company.getOrganizationCode());
            return selectVo;
        }).collect(Collectors.toList());
    }

    @Override
    public List<SelectVo> selectInfoWithOutPlant() {
        LambdaQueryWrapper<ComCompany> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ComCompany::getId, ComCompany::getCompanyName);
        wrapper.eq(ComCompany::getDelFlag, "0");
        wrapper.ne(ComCompany::getIsSewagePlant, "1");
        List<ComCompany> companies = this.list(wrapper);
        return companies.stream().map(company -> {
            SelectVo selectVo = new SelectVo();
            selectVo.setId(company.getId());
            selectVo.setName(company.getCompanyName());
            return selectVo;
        }).collect(Collectors.toList());
    }
}




